<template>
  <view :data-theme="theme">
    <!-- 导航栏 -->
    <view class="cart_nav" style="height: 20rpx;">
      <!-- #ifndef APP-PLUS -->
      <nav-bar 
        iconColor="#fff" 
        ref="navBarRef" 
        :isBackgroundColor="false" 
        navTitle="收银台"
        :leftBtn="{
          icon: 'icon-fanhui', 
          text: '返回', 
          onClick: () => goBack() 
        }"
        :rightBtn="{
          icon: 'icon-shouye', 
          text: '首页', 
          onClick: () => goHome() 
        }"
      />
      <!-- #endif -->
    </view>

    <!-- 支付信息区域 -->
    <view class="payment-info-box">
      <view class="info-row">
        <text class="label">您需要支付</text>
        <view class="countdown-wrapper">
          <text class="countdown-label">剩余支付时间：</text>
          <uni-countdown :show-day="false" :second="timeupSecond" @timeup="timeup" />
        </view>
      </view>
      <view class="amount">{{ paymentAmount }} 元</view>
      <view class="info-row">
        <text class="plate-number">{{ currentcarNum }} 订单金额</text>
        <text class="price">{{ attributes.serviceFee }} 元</text>
      </view>
    </view>

    <!-- 支付方式选择 -->
    <view class="deduction-box">
      <view class="deduction-item">
        <view class="left-section">
          <image class="icon" src="../../../static/tabBar/wx.png"></image>
          <view class="text-section">
            <text class="deduction-label">微信支付</text>
            <text class="points-info">使用微信付款</text>
          </view>
        </view>
        <CustomCheckbox 
          v-model="isWechatChecked" 
          value="wechat" 
          @change="handleWechatChange"
        />
      </view>

      <view class="deduction-item">
        <view class="left-section">
          <image class="icon" src="../../../static/tabBar/yl.png"></image>
          <view class="text-section">
            <text class="deduction-label">云闪付支付</text>
            <text class="points-info">使用银联云闪付</text>
          </view>
        </view>
        <view v-show="false">
          <CustomCheckbox 
            v-model="isUnionChecked" 
            value="union" 
            @change="handleUnionChange"
          />
        </view>
      </view>
    </view>

    <!-- 停车信息区域 -->
    <view class="park-info-box">
      <view class="content"> 
        <view class="title-line">
          <image class="icon2" src="../../../static/tabBar/message.png"></image>
          <text class="title-text">停车信息</text>
        </view>
        <view class="content-bottom"> 
          <view class="content-line">
            <text class="label">入场时间：</text>
            <text class="value">{{ attributes.startTime }}</text>
          </view>
          <view class="content-line">
            <text class="label">停车时长：</text>
            <text class="value">{{ formattedServiceTime }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button @click="goBack" class="common-button">取消</button>
      <button @click="payFee" class="common-button">支付</button>     
    </view>

    <view class="login-container">
       <button @click="goToLogin" class="common-button login-button">登录</button>
    </view>
  </view> 
</template>

<script>
import { postIntegralUser } from '@/api/user.js'
import { addChargeInfo, createPayOrder, updateTcyPlatformOrderBy, freeFull } from '@/api/parking.js'
import CustomCheckbox from '@/components/CustomCheckbox/index.vue'
import { onGetPreOrder } from '@/libs/order'
import { HTTP_PARKING_REQUEST_URL } from '@/config/app';

export default {
  components: { CustomCheckbox },
  data() {
    return {
      theme: 'default',
      paymentAmount: 0.0,        // 实付总金额
      currentcarNum: '',          // 当前车牌号
      isWechatChecked: false,     // 微信支付
      isUnionChecked: false,      // 云闪付
      timeupSecond: 180,          // 倒计时时间（3分钟=180秒）
      pointDeduction: false,      // 积分抵扣状态
      couponDeduction: false,     // 停车券抵扣状态
      attributes: {               // 订单信息
        startTime: '',            // 入场时间
        serviceTime: 0,           // 停车时长（单位：秒）
        discountFee: '',          // 优惠金额
        serviceFee: '',           // 订单金额
        parkCode: '',             // 停车场编号
        carNo: '',                // 车牌号
        parkName: '',             // 停车场名称
        goodName: ''              // 商品名称
      },
      ruleConfig: {},             // 规则配置
      pointExchangeRatio: 0,      // 积分兑换比例（积分/小时）
      pointDeductionLimit: 0,     // 单日积分抵扣上限（小时）
      nonMemberFee: 0,            // 非会员收费标准
      originalPoints: '',         // 原始积分
      outTradeNo: '',             // 外部交易号
      payOrderId: '',             // 支付订单编号
      openid: '',                 // 用户openid
      phone: '',                  // 用户手机号
      paymentTimer: null          // 支付超时定时器
    }
  },
  computed: {
    // 计算属性：将秒转换为时分秒格式
    formattedServiceTime() {
      const seconds = this.attributes.serviceTime || 0;
      if (seconds <= 0) return '0秒';
      
      const hours = Math.floor(seconds / 3600);
      const remainingSeconds = seconds % 3600;
      const minutes = Math.floor(remainingSeconds / 60);
      const secs = remainingSeconds % 60;
      
      let result = '';
      if (hours > 0) result += `${hours}小时`;
      if (minutes > 0) result += `${minutes}分`;
      if (secs > 0 || (hours === 0 && minutes === 0)) result += `${secs}秒`;
      
      return result;
    }
  },
  onLoad(options) {
    // 接收并解析参数
    this.currentcarNum = decodeURIComponent(options.carNum || '');
    console.log('参数this.currentcarNum', this.currentcarNum);
    this.openid = decodeURIComponent(options.openid || '');
    this.phone = decodeURIComponent(options.phone || '');
    
    // 解析订单属性
    try {
      const parsedAttr = options.attributes 
        ? JSON.parse(decodeURIComponent(options.attributes)) 
        : { startTime: '', serviceTime: 0, discountFee: '', serviceFee: '', parkCode: '' };
      
      // 确保 serviceTime 是数字类型
      this.attributes = {
        ...parsedAttr,
        serviceTime: parseInt(parsedAttr.serviceTime, 10) || 0
      };

      this.ruleConfig = this.attributes.ruleConfig;
      console.log('规则配置：', this.ruleConfig);

      if (this.ruleConfig != null && this.ruleConfig != undefined && this.ruleConfig != 'undefined') {
        if (this.ruleConfig.pointDeduction == '1') {
          this.pointDeduction = true;
        }
        if (this.ruleConfig.couponDeduction == '1') {
          this.couponDeduction = true;
        }
        this.nonMemberFee = this.ruleConfig.nonMemberFee;
        this.pointExchangeRatio = this.ruleConfig.pointExchangeRatio;
        this.pointDeductionLimit = this.ruleConfig.pointDeductionLimit;
      }
    } catch (error) {
      console.error('解析订单属性失败', error);
      this.attributes = { startTime: '', serviceTime: 0, discountFee: '', serviceFee: '', parkCode: '' };
    }
    
    // 初始化支付金额
    this.initPaymentAmount();
    console.log('订单属性：', this.attributes);
  },
  onUnload() {
    // 页面卸载时清除定时器
    if (this.paymentTimer) {
      clearTimeout(this.paymentTimer);
    }
  },
  methods: {
    // 初始化支付金额
    initPaymentAmount() {
      if (this.attributes.serviceFee) {
        this.paymentAmount = parseFloat(this.attributes.serviceFee);
        console.log('初始支付金额：', this.paymentAmount);      
      }
    },

    // 微信支付状态
    handleWechatChange(isChecked) {
      this.isWechatChecked = isChecked
    },

    // 云闪付支付状态（禁用状态，仅演示）
    handleUnionChange(isChecked) {
      this.isUnionChecked = isChecked
    },

    // 返回上一页
    goBack() {
      // 返回前清除定时器并更新订单状态为取消
      if (this.paymentTimer) {
        clearTimeout(this.paymentTimer);
        this.cancelOrder();
      }
      uni.navigateBack({ delta: 1 })
    },

    // 回到首页
    goHome() {
      // 回首页前清除定时器并更新订单状态为取消
      if (this.paymentTimer) {
        clearTimeout(this.paymentTimer);
        this.cancelOrder();
      }
      uni.switchTab({ url: '/pages/index/index' })
    },

    // 取消订单
    cancelOrder() {
      console.log('取消订单');
      // if (this.outTradeNo) {
      //   const params = {
      //     updateBy: uni.getStorageSync('phone') || this.phone,
      //     outTradeNo: this.outTradeNo,
      //     status: "03" // 03表示已取消
      //   };
      //   this.updateTcyPlatformOrderBy(params);
      // }
    },

    payFee() {
      console.log('支付金额：', this.paymentAmount);

      if (this.paymentAmount == 0) {
        uni.showModal({
          title: '提示',
          content: '您无需支付,请问是否离场？',
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              this.notifyParkingLot();
              uni.redirectTo({
                url: '/pages/parking/parking_pay/index'
              });
            } else if (res.cancel) {
              console.log('用户取消了支付操作');
            }
          }
        });
      } else {
        if (!this.isWechatChecked) {
          return uni.showToast({ title: '请选择微信支付', icon: 'none' });
        }
        
        const openid = uni.getStorageSync('openid');
        if (!openid || openid === 'null' || openid === 'undefined') {
          wx.login({
            success: (res) => {
              console.log('前端获取code:', res.code);
              if (res.code) {
                wx.request({
                  url: `${HTTP_PARKING_REQUEST_URL}/system/memberCar/login`,
                  method: 'GET',
                  data: { code: res.code },
                  success: (result) => {
                    uni.setStorageSync('openid', result.data.data);
                    setTimeout(() => { 
                      this.zhifu();
                    }, 1000);
                  }
                });
              } else {
                console.error('获取用户登录态失败', res);
              }
            }
          });
        } else {
          this.zhifu();
        }
      }
    },

    zhifu() {
      // 构建符合后端要求的请求参数
      const payOrderParams = {
        subject: this.attributes.carNo + " , " + this.attributes.parkName + " 停车场",
        body: "车牌号描述" + this.attributes.goodName,
        totalAmount: this.paymentAmount,
        openId: uni.getStorageSync('openid'),
        createBy: this.phone,
        channel: "WXPAY",
        orderSource: "停车费",
        orderType: "01",
        subAppId: "wx478316eb07549696",//小程序appid
        tradeType: "WX_LITE",
        carNum: this.attributes.carNo//车牌号
      };

      console.log('支付参数：', payOrderParams);

      createPayOrder(payOrderParams).then(res => {
        console.log('调起微信支付成功', res);

        const payData = JSON.parse(res.data.payData);
        this.outTradeNo = res.data.mchOrderNo;
        this.payOrderId = res.data.payOrderId;

        // 把返回的订单参数，赋值给订单表
        let params = {
          updateBy: this.phone,
          outTradeNo: this.outTradeNo,
          payOrderId: res.data.payOrderId
        };
        console.log('更新订单表参数：', params);
        
        updateTcyPlatformOrderBy(params).then(res => {
          console.log('更新订单表成功', res);

          // 设置3分钟超时定时器
          this.paymentTimer = setTimeout(() => {
            this.handlePaymentTimeout();
          }, 1 * 60 * 1000);

          wx.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.package,
            signType: payData.signType,
            paySign: payData.paySign,
            success: (res) => {
              // 清除定时器
              clearTimeout(this.paymentTimer);
              console.log('支付成功', res);
             
              // 再次更新订单表，状态改成已支付
              let params = {
                updateBy: uni.getStorageSync('phone'),
                outTradeNo: this.outTradeNo,
                status: "02"
              };
              this.updateTcyPlatformOrderBy(params);
              
              // 通知车场支付结果
              this.notifyParkingLot();

              // 停车费
              const orderSource = "停车费" + this.attributes.carNo; 
        
              uni.redirectTo({
                url: `/pages/parking/pay_success/index?` +
                    `orderType=${encodeURIComponent(orderSource)}&` +
                    `orderAmount=${encodeURIComponent(this.paymentAmount)}&` +
                    `orderId=${encodeURIComponent(this.payOrderId)}`
              });
            },
            fail: (err) => {
              // 清除定时器
              clearTimeout(this.paymentTimer);
              console.error('支付失败', err);
              
              // 支付失败时更新订单状态为取消
              this.cancelOrder();
              
              // 显示支付失败提示
              uni.showToast({
                title: err.errMsg || '支付失败',
                icon: 'none'
              });
            }
          });

        }).catch(err => {
          console.error('更新订单表失败', err);
        });

      }).catch(err => {
        console.error('调起微信支付失败', err);
        uni.showModal({
          title: '网络异常',
          content: `请求失败：${JSON.stringify(err)}`,
          showCancel: false
        });
      });
    },

    // 处理支付超时
    handlePaymentTimeout() {
      console.log('支付超时，自动取消');
      
      // 更新订单状态为已取消
      let params = {
        updateBy: uni.getStorageSync('phone') || this.phone,
        outTradeNo: this.outTradeNo,
        status: "03" // 03表示已取消
      };
      
      this.updateTcyPlatformOrderBy(params)
        .then(() => {
          uni.showToast({
            title: '支付超时已取消',
            icon: 'none'
          });
          
          // 跳转到支付失败页面
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/parking/pay_fail/index?orderId=${encodeURIComponent(this.payOrderId)}`
            });
          }, 1500);
        })
        .catch(err => {
          console.error('更新订单状态失败', err);
        });
    },

    // 通知车场支付结果
    notifyParkingLot() {
      console.log('参数this.attributes：打印', this.attributes);
      const params = { 
        carNo: this.currentcarNum,
        parkCode: 'p240199697'
      };
      console.log('全免参数：', params);
      freeFull(params).then(res => {
        console.log('全免成功：', res)
      }).catch(err => {
        console.error('全免失败：', err)
      })
    },

    // 更新订单表的支付状态
    updateTcyPlatformOrderBy(params) {
      updateTcyPlatformOrderBy(params).then(res => {
        console.log('更新订单表的支付状态成功：', res)
      }).catch(err => {
        console.error('更新订单表的支付状态失败：', err)
      })
    },

    // 倒计时结束
    timeup() {
      // 倒计时结束时处理超时
      if (this.paymentTimer) {
        clearTimeout(this.paymentTimer);
      }
      this.handlePaymentTimeout();
    },

    goToLogin() {
      uni.navigateTo({
        url: '/pages/users/wechat_login/index_of_no'
      });
    }
  }
}
</script>

<style scoped lang="scss">
/* 导航栏 */
.cart_nav {
  position: relative;
  z-index: 99;
}

/* 支付信息区域 */
.payment-info-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 26rpx;
  color: #666;
}

.countdown-wrapper {
  display: flex;
  align-items: center;
  color: #999;
}

.amount {
  font-size: 40rpx;
  color: #FA6401;
  font-weight: bold;
  text-align: center;
  margin: 20rpx 0;
}

.discount-row {
  color: #FA6401;
}

.discount-price {
  font-weight: bold;
}

/* 积分与优惠券区域 */
.deduction-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.deduction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.deduction-item.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.left-section {
  display: flex;
  align-items: center;
}

.icon {
  width: 72rpx;
  height: 72rpx;
  margin-right: 20rpx;
}

.text-section {
  display: flex;
  flex-direction: column;
}

.deduction-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.points-info, .coupon-tip {
  font-size: 24rpx;
  color: #666;
}

/* 停车信息区域 */
.park-info-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.title-line {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.icon2 {
  width: 44rpx;
  height: 44rpx;
  margin-right: 8rpx;
}

.content-bottom {
  padding-left: 44rpx;
}

.content-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  font-size: 26rpx;
  color: #666;
}

.content-line .value {
  color: #333;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  left: 0;
  right: 0;
  height: 80rpx;
  background-color: #f5f5f5;
  padding: 0 30rpx;
  z-index: 10;
}

.common-button {
  width: 45%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #FE725C;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin: 0 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(254, 114, 92, 0.3);
}

/* 登录按钮容器 */
.login-container {
  position: fixed;
  bottom: 20rpx;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  padding: 0 40rpx;
  z-index: 9;
}

.login-button {
  width: 100%;
  max-width: 600rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #ffffff;
  color: #333;
  font-size: 28rpx;
  border-radius: 40rpx;
  border: 1rpx solid #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
</style>